<template>
    <div class="page-content">
        <h3>新客专享</h3>
        <el-row>
            <el-col :xs="24" :sm="12" :lg="6" class="el-col2">
                <el-button @click="showDialog" v-ripple>新增活动</el-button>
            </el-col>
            <el-col :xs="24" :sm="12" :lg="3">
                <el-form :model="searchForm">
                    <el-form-item prop="queryCondition">
                        <el-input placeholder="请输入活动名称" v-model="searchForm.activityName" @blur="getData"
                            clearable></el-input>
                    </el-form-item>
                </el-form>
            </el-col>
        </el-row>

        <art-table :data="tableData" :loading="tableLoading" :currentPage="pageNum" :pageSize="pageSize"
            :total="pageTotal" @current-change="currentChange" @size-change="sizeChange">
            <template #default>
                <!--                <el-table-column label="活动ID" prop="id" width="120" align="center" />-->
                <el-table-column label="活动名称" prop="activityName" align="center" />
                <el-table-column label="活动时间" prop="createTime" align="center">
                    <template #default="scope">
                        <div>
                            <el-tag type="primary">起</el-tag> {{ formatDate(scope.row.startTime) }}
                        </div>
                        <div style="margin-top: 5px;">
                            <el-tag type="danger">止</el-tag> {{ formatDate(scope.row.endTime) }}
                        </div>
                    </template>
                </el-table-column>
                <el-table-column label="活动赠送" prop="activityContentAoList" align="center">
                    <template #default="scope">
                        <span v-if="scope.row.activityContentAoList[0].activityCommodityAoList.length">
                            <span>
                                <template
                                    v-for="(item, idx) in scope.row.activityContentAoList[0].activityCommodityAoList"
                                    :key="item.id">
                                    <span>{{ item.name }}</span>
                                    <span
                                        v-if="idx < scope.row.activityContentAoList[0].activityCommodityAoList.length - 1">,
                                    </span>
                                </template>
                            </span>
                        </span>
                        <span v-else>无</span>
                    </template>
                </el-table-column>
                <el-table-column label="创建时间" prop="createTime" align="center">
                    <template #default="scope">
                        {{ formatDate(scope.row.createTime) }}
                    </template>
                </el-table-column>
                <el-table-column label="活动状态" prop="activityStatus" align="center">
                    <template #default="scope">
                        <el-tag type="primary" v-if="scope.row.activityStatus === 1">进行中</el-tag>
                        <el-tag type="info" v-if="scope.row.activityStatus === 0">未开始</el-tag>
                        <el-tag type="warning" v-if="scope.row.activityStatus === 2">已结束</el-tag>
                        <el-tag type="danger" v-if="scope.row.activityStatus === 3">已停用</el-tag>
                    </template>
                </el-table-column>
                <el-table-column label="开启状态" prop="status" #default="scope" align="center">
                    <el-switch v-model="scope.row.status" :inactive-value="0" :active-value="1"
                        @change="EditStatus(scope.row)" />
                </el-table-column>
                <el-table-column fixed="right" label="操作" width="200px" align="center">
                    <template #default="scope">
                        <el-tooltip class="box-item" effect="dark" content="领取记录" placement="top-start">
                            <button-table type="record" @click="involvedClick(scope.row.id)" />
                        </el-tooltip>
                        <el-tooltip class="box-item" effect="dark" content="编辑" placement="top-start">
                            <button-table type="edit" @click="buttonMoreClick(scope.row)" />
                        </el-tooltip>
                        <el-tooltip class="box-item" effect="dark" content="删除" placement="top-start">
                            <button-table type="delete" @click="deleteRole(scope.row.id)" />
                        </el-tooltip>
                    </template>
                </el-table-column>
            </template>
        </art-table>
    </div>
</template>

<script setup lang="ts">
import { ElMessage, ElMessageBox } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
import { activityGetPage, delActivity, editActive } from '@/api/marketing'
import { useRouter } from 'vue-router'
const router = useRouter()
const searchForm = reactive({
    activityName: ''
})

const tableData = ref([])

const showDialog = () => {
    router.push({ path: '/result/activeRules' })
}

const buttonMoreClick = (row: any) => {
    router.push({ path: '/result/activeRules', query: { id: row.id } })
}
const involvedClick = (id: number) => {
    router.push({ path: '/result/involvedRecord', query: { id } })
}

const deleteRole = (id: string) => {
    ElMessageBox.confirm('确定删除该活动吗？', '删除确认', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'error'
    }).then(async () => {
        const res = await delActivity(id)
        if (res.code === '00000') {
            ElMessage.success('删除成功')
            getData()
        }

    })
}

const formatDate = (date: string) => {
    return new Date(date)
        .toLocaleString('zh-CN', {
            year: 'numeric',
            month: '2-digit',
            day: '2-digit',
            hour: '2-digit',
            minute: '2-digit',
            second: '2-digit'
        })
        .replace(/\//g, '-')
}

const currentChange = (val: number) => {
    pageNum.value = val
    getData()
}

const sizeChange = (val: number) => {
    pageSize.value = val
    pageNum.value = 1
    getData()
}

const tableLoading = ref(false)
const pageNum = ref(1)
const pageSize = ref(10)
const pageTotal = ref(0)

const filterEmptyValues = (obj: any) => {
    const result: any = {}
    for (const key in obj) {
        if (obj[key] !== '' && obj[key] !== null && obj[key] !== undefined) {
            result[key] = obj[key]
        }
    }
    return result
}

const getData = async () => {
    tableLoading.value = true
    try {
        const params = filterEmptyValues(searchForm)
        const res = await activityGetPage({
            pageSize: pageSize.value,
            pageNum: pageNum.value,
            activityType: '02',
            ...params
        })
        if (res.code === '00000') {
            tableData.value = res.data.list
            pageTotal.value = res.data.total
        }
    } catch { } finally {
        tableLoading.value = false
    }

}

const EditStatus = async (row: any) => {
    const obj: any = {
        activityName: row.activityName,
        image: row.image,
        startTime: row.startTime ? formatDate(row.startTime) : '',
        endTime: row.endTime ? formatDate(row.endTime) : '',
        activityType: '02',
        status: row.status,
        activityContentVoList: [{
            targetType: '01',
            giftType: '04',
            giftRefIds: row.activityContentAoList && row.activityContentAoList.length > 0 && row.activityContentAoList[0].giftRefIds ? row.activityContentAoList[0].giftRefIds : '',
            giftQuantity: 1,
            limitPerUser: 1
        }]
    }
    try {
        const res = await editActive(row.id, obj)
        if (res.code === '00000') {
            ElMessage.success('修改成功')
        }
    } catch (e) {
    } finally {
        await getData()
    }
}
onMounted(() => {
    getData()
})
</script>

<style lang="scss" scoped>
.page-content {
    .svg-icon {
        width: 1.8em;
        height: 1.8em;
        overflow: hidden;
        vertical-align: -8px;
        fill: currentcolor;
    }

    h3 {
        font-weight: bold;
        margin-bottom: 20px;
    }
}

:deep(.el-row) {
    justify-content: space-between;
}
</style>